package com.fafa.pos.activity;

import android.app.AlertDialog;
import android.content.Intent;
import android.media.RingtoneManager;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewCompat;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.*;
import com.fafa.pos.R;
import com.fafa.pos.dao.*;
import com.fafa.pos.dao.impl.CardInfoDaoImpl;
import com.fafa.pos.dao.impl.ConfigDaoImpl;
import com.fafa.pos.dao.impl.ConsumeInfoDaoImpl;
import com.fafa.pos.dao.impl.VipInfoDaoImpl;
import com.fafa.pos.pojo.CardInfo;
import com.fafa.pos.pojo.Config;
import com.fafa.pos.pojo.ConsumeInfo;
import com.fafa.pos.pojo.VipInfo;
import com.fafa.pos.util.MyActivityManager;
import com.fafa.pos.util.SharedPreferencesHelper;
import com.fafa.pos.util.WebServiceUtil;
import com.fafa.pos.util.WebServiceValueCastUtil;
import com.fafa.pos.vo.CurUser;
import com.fafa.pos.vo.Status;
import com.fafa.pos.vo.WSResult;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class OffLineDataUploadActivity extends TitleActivity {

    private SharedPreferencesHelper sharedPreferencesHelper;
    private String userCode;
    //dao相关
    private DBUtil dbUtil;
    private IConsumeInfoDao consumeInfoDao;
    private IVipInfoDao vipInfoDao;
    private ICardInfoDao cardInfoDao;
    private IConfigDao configDao;

    //view 相关
    private TextView offLineTotalCount;
    private ListView offLineDetail;
    private RelativeLayout uploading;

    private Object obj = new Object();

    private boolean uploadFlag = false;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_off_line_sale);

        //设置状态栏和标题栏同色
        Window window = this.getWindow();
        //取消设置透明状态栏,使 ContentView 内容不再覆盖状态栏
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);

        //需要设置这个 flag 才能调用 setStatusBarColor 来设置状态栏颜色
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        //设置状态栏颜色
        window.setStatusBarColor(getResources().getColor(R.color.LoginBlue));

        ViewGroup mContentView = (ViewGroup) this.findViewById(Window.ID_ANDROID_CONTENT);
        View mChildView = mContentView.getChildAt(0);
        if (mChildView != null) {
            //注意不是设置 ContentView 的 FitsSystemWindows, 而是设置 ContentView 的第一个子 View . 预留出系统 View 的空间.
            ViewCompat.setFitsSystemWindows(mChildView, true);
        }


        //加入activity管理
        MyActivityManager.getInstance().addActivity(this);

        setTitle("离线数据");
        showBackwardView(R.string.text_back,true);
        showForwardView(R.string.text_upload,true);


        sharedPreferencesHelper = new SharedPreferencesHelper(
                OffLineDataUploadActivity.this, "PosUserInfo");//实例化sharedPreferencesHelper工具类

        initDao();
        initView();
        initEvent();

    }

    private void initDao() {
        dbUtil = new DBUtil(getApplicationContext().getFilesDir().getAbsoluteFile()+"/pos.db");
        consumeInfoDao = new ConsumeInfoDaoImpl(dbUtil);
        vipInfoDao = new VipInfoDaoImpl(dbUtil);
        cardInfoDao = new CardInfoDaoImpl(dbUtil);
        configDao = new ConfigDaoImpl(dbUtil);
    }

    private void initView() {
        offLineTotalCount = (TextView) findViewById(R.id.offLineTotalCount);
        offLineDetail = (ListView) findViewById(R.id.offLineDetail);
        uploading = (RelativeLayout) findViewById(R.id.uploading);

        double total = 0.00;
        List<Map<String,Object>> data = new ArrayList<Map<String, Object>>();
        List<ConsumeInfo> consumeInfos = consumeInfoDao.getAllOffLineConsumeInfo();
        if(consumeInfos!=null){
            for (ConsumeInfo consumeInfo:consumeInfos) {
                Map<String,Object> dataItem = new HashMap<String,Object>();
                dataItem.put("money","消费 : "+consumeInfo.getMoney()+"元");
                dataItem.put("vipName","");
                CardInfo cardInfo = cardInfoDao.getCard(consumeInfo.getCardCode());
                if(cardInfo!=null){
                    VipInfo vipInfo = vipInfoDao.getVipInfo(cardInfo.getVipId());
                    if(vipInfo!=null){
                        dataItem.put("vipName",vipInfo.getVipName());
                        dataItem.put("vipCode",vipInfo.getVipCode());
                    }
                }
                dataItem.put("date",consumeInfo.getDate());

                if(consumeInfo.getErrorMsg()!=null){//若有错误信息则展示
                    dataItem.put("errorMsg",consumeInfo.getErrorMsg());
                }else{
                    dataItem.put("errorMsg","");
                }

                if("1".equals(consumeInfo.getIsUpLoad())){
                    dataItem.put("select",R.drawable.select);
                }else{
                    dataItem.put("select",R.drawable.selected);
                }

                data.add(dataItem);

                total+= Double.parseDouble(consumeInfo.getMoney());
            }
            DecimalFormat df = new DecimalFormat("0.00");
            offLineTotalCount.setText(consumeInfos.size()+"条,合计"+df.format(total)+"元");
        }
        //实例化适配器
        SimpleAdapter simpleAdapter = new SimpleAdapter(OffLineDataUploadActivity.this,data,R.layout.off_line_detail_item,new String[]{"money","vipName","date","vipCode","errorMsg","select"},new int[]{R.id.money,R.id.vipName,R.id.date,R.id.vipCode,R.id.uploadErrorMsg,R.id.select});
        //ListView 加载适配器
        offLineDetail.setAdapter(simpleAdapter);


    }

    private void initEvent() {
    }

    private Handler msgHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 1://上传标志显示/不显示切换
                    if(uploading.getVisibility()==View.VISIBLE){
                        uploading.setVisibility(View.INVISIBLE);
                    }else{
                        uploading.setVisibility(View.VISIBLE);
                    }
                    break;
                case 2://上传成功，弹框，初始化view
                    TextView tv = new TextView(OffLineDataUploadActivity.this);
                    tv.setPadding(60,20,60,20);
                    String[] count = msg.obj.toString().split("-");
                    tv.setText(msg.obj.toString());
                    //tv.setText("总共上传"+count[0]+"条,成功"+count[1]+"条,失败"+(Integer.parseInt(count[0])-Integer.parseInt(count[1]))+"条");
                    AlertDialog.Builder builder = new AlertDialog.Builder(OffLineDataUploadActivity.this);
                    builder.setTitle("上传信息").setView(tv).setPositiveButton("确定",null);
                    builder.show();
                    initView();
                    break;
            }
        }
    };

    @Override
    protected void onForward(View forwardView) {
        if(!uploadFlag){
            uploadFlag = true;
            List<ConsumeInfo> consumeInfos = consumeInfoDao.getAllOffLineConsumeInfo();
            if(consumeInfos.size()>0){
                msgHandler.sendEmptyMessage(1);
            }
            upload(consumeInfos);
        }
    }

    private void upload(final List<ConsumeInfo>  consumeInfos){
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("~~~~~~~~~~~~~~~~~~~~~");
                int errorCount = 0;
                StringBuffer uploadStr = new StringBuffer();
                Config config = configDao.getConfig();
                userCode = sharedPreferencesHelper.getSharedPreference("userCode", "").toString().trim();
                //拼装上传字符串
                for (ConsumeInfo consumeInfo:consumeInfos) {
                    uploadStr.append(consumeInfo.getId()
                            +"_" +consumeInfo.getCardCode()
                            +"_"+consumeInfo.getMoney()
                            +"_" +config.getProperties().get("posCode")
                            +"_" +userCode
                            +"_" + consumeInfo.getDate().replaceAll(" ","_")+"|");
                }
                String uploadData = uploadStr.substring(0,uploadStr.length()-1);

                String msg = null;

                Map<String, Object> parameters = new HashMap<>();
                parameters.put("batchData", uploadData);

                SoapObject so = WebServiceUtil.getResponse(config, "ProcessBatchSales", parameters, 1000 * 15);

                if(so!=null){
                    SoapPrimitive sp = (SoapPrimitive) so.getProperty("ProcessBatchSalesResult");
                    WSResult wsResult = WebServiceValueCastUtil.cast(sp.toString());

                    if(wsResult.getResultCode()==0){

                        //1. 写个for循环
                        //2. 解析
                        //3. 成功   consumeInfoDao.setIsUpLoad(consumeInfo.getId(),"1");
                        //4. 失败   consumeInfoDao.saveErrorMsg(consumeInfo.getId(),errorMsg);
                        //5. show total
                        for(Map<String,Object> retItem:(ArrayList<Map<String,Object>>)wsResult.getResultValues().get("List")){

                            System.out.println("IS_SCUCESS:"+retItem.get("IS_SCUCESS"));
                            if(retItem.get("IS_SCUCESS")!=null&&"1".equals(retItem.get("IS_SCUCESS").toString())){
                                consumeInfoDao.setIsUpLoad(retItem.get("OFFLINE_CODE").toString(),"1");
                                System.out.println("111111111111111");
                            }else{
                                if(retItem.get("ERROR_MSG")!=null){
                                    System.out.println("222222222222222222222222");
                                    consumeInfoDao.saveErrorMsg(retItem.get("OFFLINE_CODE").toString(),retItem.get("ERROR_MSG").toString());
                                }
                            }
                        }
                        if(consumeInfos.size()>0){
                            msg = "单据总数:"+wsResult.getResultValues().get("TOTAL_CNT").toString()+"\n"
                                    +"成功数量:"+wsResult.getResultValues().get("SUCCESS_CNT").toString()+"\n"
                                    +"失败数量:"+wsResult.getResultValues().get("FAIL_CNT").toString()+"\n"
                                    +"超扣数量:"+wsResult.getResultValues().get("OVER_BALANCE_CNT").toString();
                        }
                    }else{
                        msg = wsResult.getResultValues().get("message").toString();
                    }
                }else{
                    msg = "连接超时";
                }
                if(msg!=null){
                    msgHandler.sendEmptyMessage(1);
                    Message message = new Message();
                    message.what = 2;
                    message.obj = msg;
                    msgHandler.sendMessage(message);
                }
            }
        });
        thread.start();
    }

}
